# Copyright 2020 InterDigital Communications, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import math
import random
import shutil
import sys
import time
import os

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision

from torch.utils.data import DataLoader
from torchvision.utils import save_image
from compressai.models.util.pos_embed import interpolate_pos_embed
from torchvision import transforms

from compressai.datasets import ImageFolder
from compressai.zoo import models

from pytorch_msssim import ms_ssim
import torch.nn.functional as F

import numpy as np

from torch.utils.tensorboard import SummaryWriter


class RateDistortionLoss(nn.Module):
    """Custom rate distortion loss with a Lagrangian parameter."""

    def __init__(self, lmbda=1e-2):
        super().__init__()
        self.mse = nn.MSELoss()
        self.lmbda = lmbda

    def forward(self, output, target):
        N, _, H, W = target.size()
        out = {}
        num_pixels = N * H * W

        out["bpp_loss"] = sum(
            (torch.log(likelihoods).sum() / (-math.log(2) * num_pixels))
            for likelihoods in output["likelihoods"].values()
        )
        out["mse_loss"] = self.mse(output["x_hat"], target)
        out["loss"] = self.lmbda * 255 ** 2 * out["mse_loss"] + out["bpp_loss"]
        return out

def PSNR(a: torch.Tensor, b: torch.Tensor) -> float:
    mse = F.mse_loss(a, b).item()
    return -10 * math.log10(mse)

def inference(output, target):
    psnr = 0.0
    ssim = 0.0
    out = {}
    N, _, H, W = target.size()
    # for i in range(N):
        # psnr += PSNR(target[i,:,:,:], output["x_hat"][i,:,:,:])
        # ssim += ms_ssim(target[i,:,:,:], output["x_hat"][i,:,:,:], data_range=1.0).item()
    
    out["psnr"] = PSNR(target, output["x_hat"])
    out["ms-ssim"] = ms_ssim(target, output["x_hat"], data_range=1.0).item()

    return out

class AverageMeter:
    """Compute running average."""

    def __init__(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

class CustomDataParallel(nn.DataParallel):
    """Custom DataParallel to access the module methods."""

    def __getattr__(self, key):
        try:
            return super().__getattr__(key)
        except AttributeError:
            return getattr(self.module, key)


def configure_optimizers(net, args):
    """Separate parameters for the main optimizer and the auxiliary optimizer.
    Return two optimizers"""

    parameters = {
        n
        for n, p in net.named_parameters()
        if not n.endswith(".quantiles") and p.requires_grad
    }
    for n, p in net.named_parameters():
        if not n.endswith(".quantiles") and p.requires_grad:
            pass
        else:
            print(n)
    aux_parameters = {
        n
        for n, p in net.named_parameters()
        if n.endswith(".quantiles") and p.requires_grad
    }
    # print(aux_parameters)

    # Make sure we don't have an intersection of parameters
    params_dict = dict(net.named_parameters())
    inter_params = parameters & aux_parameters
    union_params = parameters | aux_parameters

    assert len(inter_params) == 0
    # assert len(union_params) - len(params_dict.keys()) == 0

    optimizer = optim.Adam(
        (params_dict[n] for n in sorted(parameters)),
        lr=args.learning_rate,
    )
    aux_optimizer = optim.Adam(
        (params_dict[n] for n in sorted(aux_parameters)),
        lr=args.aux_learning_rate,
    )
    return optimizer, aux_optimizer


total_steps = 0
writer = SummaryWriter(log_dir='./logs_my', comment='mymodel')


def train_one_epoch(
    model, criterion, train_dataloader, optimizer, aux_optimizer, epoch, clip_max_norm
):
    global total_steps
    model.train()
    device = next(model.parameters()).device
    for i, d in enumerate(train_dataloader):
        total_steps += d.shape[0]
        d = d.to(device)

        optimizer.zero_grad()
        aux_optimizer.zero_grad()

        out_net = model(d)

        img = d[:1,:,:,:].squeeze()

        out_criterion = criterion(out_net, d)
        out_criterion["loss"].backward()
        if clip_max_norm > 0:
            torch.nn.utils.clip_grad_norm_(model.parameters(), clip_max_norm)
        optimizer.step()

        aux_loss = model.aux_loss()
        aux_loss.backward()
        aux_optimizer.step()

        # display the training processing
        if (total_steps % 1000 == 0):
            output, GT = out_net['x_hat'], d
            image_out = torch.cat([output, GT], 0)
            grid = torchvision.utils.make_grid(image_out)
            writer.add_image('Epoch_(%d)_(%d)' %
                             (epoch, total_steps), grid, total_steps)

            # feature_map1 = out_net["features_encoder_out"]
            # heatmap = torch.tensor(feature_visualization(img, feature_map1[:1,:,:,:])).to(device)
            # feature_out = torch.cat([img.unsqueeze(0), heatmap.unsqueeze(0)],0)
            # writer.add_image('Epoch_(%d)_(%d)_features_encoder_out' %
            #                  (epoch, total_steps), torchvision.utils.make_grid(feature_map1[0].detach().cpu().unsqueeze(dim=1), nrow=16, normalize=False), total_steps)
            # writer.add_image('Epoch_(%d)_(%d)_heatmap' %
            #                  (epoch, total_steps), torchvision.utils.make_grid(feature_out, normalize=False), total_steps)

            # feature_map1 = out_net["features_encoder_out"]
            # feature_map2 = out_net["features_entroy_out"]
            # writer.add_image('Epoch_(%d)_(%d)_features_encoder_out' %
            #                  (epoch, total_steps), torchvision.utils.make_grid(feature_map1[0].detach().cpu().unsqueeze(dim=1), nrow=16, normalize=False), total_steps)
            # writer.add_image('Epoch_(%d)_(%d)_features_entroy_out' %
            #                  (epoch, total_steps), torchvision.utils.make_grid(feature_map2[0].detach().cpu().unsqueeze(dim=1), nrow=16, normalize=False), total_steps)

        # display the training processing
        if (total_steps % 50 == 0):
            writer.add_scalar("loss", out_criterion["loss"].item(), total_steps+1)
            writer.add_scalar("mse_loss", out_criterion["mse_loss"].item() * 255 ** 2 / 3, total_steps)
            writer.add_scalar("bpp_loss", out_criterion["bpp_loss"].item(), total_steps)
            writer.add_scalar("aux_loss", aux_loss.item(), total_steps)

        if i % 100 == 0:
            print(
                f"Train epoch {epoch}: ["
                f"{i*len(d)}/{len(train_dataloader.dataset)}"
                f" ({100. * i / len(train_dataloader):.0f}%)]"
                f'\tLoss: {out_criterion["loss"].item():.3f} |'
                f'\tMSE loss: {out_criterion["mse_loss"].item() * 255 ** 2 / 3:.3f} |'
                f'\tBpp loss: {out_criterion["bpp_loss"].item():.2f} |'
                f"\tAux loss: {aux_loss.item():.2f}"
            )


def test_epoch(epoch, test_dataloader, model, criterion):
    model.eval()
    device = next(model.parameters()).device

    loss = AverageMeter()
    bpp_loss = AverageMeter()
    mse_loss = AverageMeter()
    aux_loss = AverageMeter()
    psnr_list =[]
    ssim_list = []
    val_loss_list =[]

    with torch.no_grad():
        for d in test_dataloader:
            d = d.to(device)
            out_net = model(d)

            metrics = inference(out_net, d)
            
            # for i in range(out_net['x_hat'].shape[0]):
            #     save_image(out_net['x_hat'][i, :, :, :],
            #                './rec_imgs/' + str(time.time())+'.jpg')
            out_criterion = criterion(out_net, d)

            psnr_list.append(metrics["psnr"])
            ssim_list.append(metrics["ms-ssim"])
            val_loss_list.append(out_criterion["loss"])

            aux_loss.update(model.aux_loss())
            bpp_loss.update(out_criterion["bpp_loss"])
            loss.update(out_criterion["loss"])
            mse_loss.update(out_criterion["mse_loss"])

    print(
        f"Test epoch {epoch}: Average losses:"
        f"\tLoss: {loss.avg:.3f} |"
        f"\tMSE loss: {mse_loss.avg * 255 ** 2 / 3:.3f} |"
        f"\tBpp loss: {bpp_loss.avg:.2f} |"
        f"\tAux loss: {aux_loss.avg:.2f}\n"
    )

    save_path = 'logs_my/val.txt'
    with open(save_path,'a+') as f:
        f.write('epoch'+str(epoch)+'  '+'psnr: ' + str(format(torch.mean(torch.tensor(psnr_list)).numpy(), '.6f'))+'  ' + 'ms-ssim: ' + str(format(torch.mean(torch.tensor(ssim_list)).numpy(), '.6f'))+ '  ' + 'val_loss: ' + str(format(torch.mean(torch.tensor(val_loss_list)).numpy(), '.6f'))+ '  ' + 'bpp: ' + str(format(bpp_loss.avg, '.6f'))+'\n')
    f.close()
    return loss.avg

def save_checkpoint(state, is_best, filename):
    filename1 = filename[:-8] + '_epoch'+str(state['epoch']) + filename[-8:]
    torch.save(state, filename1)
    if is_best:
        shutil.copyfile(filename1, filename[:-8]+"_best"+filename[-8:])


def parse_args(argv):
    parser = argparse.ArgumentParser(description="Example training script.")
    parser.add_argument(
        "-m",
        "--model",
        default="stf",
        choices=models.keys(),
        help="Model architecture (default: %(default)s)",
    )
    parser.add_argument(
        "-d", "--dataset", type=str, required=True, help="Training dataset"
    )
    parser.add_argument(
        "-e",
        "--epochs",
        default=100,
        type=int,
        help="Number of epochs (default: %(default)s)",
    )
    parser.add_argument(
        "-lr",
        "--learning-rate",
        default=1e-4,
        type=float,
        help="Learning rate (default: %(default)s)",
    )
    parser.add_argument(
        "-n",
        "--num-workers",
        type=int,
        default=30,
        help="Dataloaders threads (default: %(default)s)",
    )
    parser.add_argument(
        "--lambda",
        dest="lmbda",
        type=float,
        default=1e-2,
        help="Bit-rate distortion parameter (default: %(default)s)",
    )
    parser.add_argument(
        "--batch-size", type=int, default=16, help="Batch size (default: %(default)s)"
    )
    parser.add_argument(
        "--test-batch-size",
        type=int,
        default=64,
        help="Test batch size (default: %(default)s)",
    )
    parser.add_argument(
        "--aux-learning-rate",
        default=1e-3,
        type=float,
        help="Auxiliary loss learning rate (default: %(default)s)",
    )
    parser.add_argument(
        "--patch-size",
        type=int,
        nargs=2,
        default=(256, 256),
        help="Size of the patches to be cropped (default: %(default)s)",
    )
    parser.add_argument("--cuda", action="store_true", help="Use cuda")
    parser.add_argument(
        "--save", action="store_true", default=True, help="Save model to disk"
    )
    parser.add_argument(
        "--save_path", type=str, default="ckpt/model.pth.tar", help="Where to Save model"
    )
    parser.add_argument(
        "--seed", type=float, help="Set random seed for reproducibility"
    )
    parser.add_argument(
        "--clip_max_norm",
        default=1.0,
        type=float,
        help="gradient clipping max norm (default: %(default)s",
    )
    parser.add_argument('--global_pool', action='store_true')
    parser.set_defaults(global_pool=True)
    parser.add_argument("--checkpoint", type=str,
                        default='', help="Path to a checkpoint")
    parser.add_argument("--checkpoint2", type=str,
                        default='', help="Path to a checkpoint")
    args = parser.parse_args(argv)
    return args


def main(argv):
    args = parse_args(argv)
    print(args)
    if args.seed is not None:
        torch.manual_seed(args.seed)
        random.seed(args.seed)

    train_transforms = transforms.Compose(
        [transforms.Resize([224, 224]), transforms.ToTensor()]
    )

    test_transforms = transforms.Compose(
        [transforms.Resize([224, 224]), transforms.ToTensor()]
    )

    train_dataset = ImageFolder(
        args.dataset, split="train", transform=train_transforms)
    test_dataset = ImageFolder(
        args.dataset, split="test", transform=test_transforms)

    device = "cuda" if args.cuda and torch.cuda.is_available() else "cpu"

    train_dataloader = DataLoader(
        train_dataset,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        shuffle=True,
        pin_memory=(device == "cuda"),
    )

    test_dataloader = DataLoader(
        test_dataset,
        batch_size=args.test_batch_size,
        num_workers=args.num_workers,
        shuffle=False,
        pin_memory=(device == "cuda"),
    )

    net = models[args.model]()
    net = net.to(device)

    if args.cuda and torch.cuda.device_count() > 1:
        net = CustomDataParallel(net)

    optimizer, aux_optimizer = configure_optimizers(net, args)
    print(optimizer.param_groups[0]['lr'])

    lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(
        optimizer, "min", factor=0.3, patience=4)
    criterion = RateDistortionLoss(lmbda=args.lmbda)

    last_epoch = 0

    # '''load mae encoder model'''
    # if args.checkpoint:
    #     # checkpoint = torch.load(args.checkpoint, map_location=device)

    #     # print("Load pre-trained checkpoint from: %s" % args.checkpoint)
    #     # checkpoint_model = checkpoint['model']
    #     # state_dict = net.state_dict()
    #     # # for k in ['head.weight', 'head.bias']:
    #     # #     if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape:
    #     # #         print(f"Removing key {k} from pretrained checkpoint")
    #     # #         del checkpoint_model[k]
    #     # # interpolate position embedding
    #     # interpolate_pos_embed(net, checkpoint_model)

    #     checkpoint = torch.load(args.checkpoint, map_location='cpu')
    #     checkpoint_model = checkpoint['model']
    #     # print(len(checkpoint_model))
    #     # net.load_state_dict(checkpoint['model'], strict=False)
    #     interpolate_pos_embed(net, checkpoint_model)
    #     # load pre-trained model
    #     # msg = net.load_state_dict(checkpoint_model, False)
    #     net.load_state_dict(checkpoint_model, False)

    #     checkpoint2 = torch.load(args.checkpoint2, map_location=device)
    #     net.load_state_dict2(checkpoint2["state_dict"], False)


    if args.checkpoint:  # load from previous checkpoint
        print("Loading", args.checkpoint)
        checkpoint = torch.load(args.checkpoint, map_location=device)
        last_epoch = checkpoint["epoch"] + 1
        net.load_state_dict(checkpoint["state_dict"], True)

        optimizer.load_state_dict(checkpoint["optimizer"])
        aux_optimizer.load_state_dict(checkpoint["aux_optimizer"])
        lr_scheduler.load_state_dict(checkpoint["lr_scheduler"])

    best_loss = float("inf")
    # Create the logs
    dir = os.path.join('./logs_my', 'mymodel').replace('\\', '/')
    if not os.path.exists(dir):
        os.mkdir(dir)

    total_steps = 0
    for epoch in range(last_epoch, args.epochs):
        print(f"Learning rate: {optimizer.param_groups[0]['lr']}")
        train_one_epoch(
            net,
            criterion,
            train_dataloader,
            optimizer,
            aux_optimizer,
            epoch,
            args.clip_max_norm,
        )
        print('===> Validating...')
        loss = test_epoch(epoch, test_dataloader, net, criterion)
        lr_scheduler.step(loss)

        is_best = loss < best_loss
        best_loss = min(loss, best_loss)

        if args.save:
            save_checkpoint(
                {
                    "epoch": epoch,
                    "state_dict": net.state_dict(),
                    "loss": loss,
                    "optimizer": optimizer.state_dict(),
                    "aux_optimizer": aux_optimizer.state_dict(),
                    "lr_scheduler": lr_scheduler.state_dict(),
                },
                is_best,
                args.save_path,
                # args.save_path[:-8]+'_epoch'+str(epoch)+args.save_path[-8:],
            )


if __name__ == "__main__":
    main(sys.argv[1:])
